package com.jctrip.hotel.common.util;


import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @Author henry
 * @Date 2023/7/2 13:27
 * @Description
 */
@Slf4j
public class Okhttp3Utils {
    /**
     * xml格式post请求接口调用
     *
     * @param url 接口地址
     * @param xmlStr xml格式请求参数体
     */
    public static String postXml(String url, String xmlStr) {
        log.info("postXml url :{} , xmlStr :{}", url, xmlStr);
        RequestBody body = RequestBody.create(MediaType.parse("application/xml"), xmlStr);
        Request requestOk = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        Response response;
        try {
            response = new OkHttpClient().newCall(requestOk).execute();
            String jsonString = response.body().string();
            if (response.isSuccessful()) {
                return jsonString;
            }
            throw new RuntimeException(response.message());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * xml格式post请求接口调用
     *
     * @param url 接口地址
     * @param xmlStr xml格式请求参数体
     */
    public static String postFormData(String url, String xmlStr) {
        log.info("postFormDataXml url :{} , xmlStr :{}", url, xmlStr);
        RequestBody body = new FormBody.Builder()
                .add("xmlRequest", xmlStr)
                .build();
        Request requestOk = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response;
        try {
            response = new OkHttpClient().newCall(requestOk).execute();
            String jsonString = response.body().string();
            if (response.isSuccessful()) {
                return jsonString;
            }
            throw new RuntimeException(response.message());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
